import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, logout as apiLogout, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')

  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.is_admin || false)

  const login = async (credentials) => {
    try {
      const response = await apiLogin(credentials)
      token.value = response.token
      user.value = response.user
      localStorage.setItem('token', token.value)
      return response
    } catch (error) {
      throw error
    }
  }

  const logout = async () => {
    try {
      await apiLogout()
    } finally {
      token.value = ''
      user.value = null
      localStorage.removeItem('token')
    }
  }

  const checkLoginStatus = async () => {
    if (token.value) {
      try {
        const userInfo = await getUserInfo()
        user.value = userInfo
      } catch (error) {
        token.value = ''
        user.value = null
        localStorage.removeItem('token')
      }
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    isAdmin,
    login,
    logout,
    checkLoginStatus
  }
})
